<?php
namespace app\common\service;


use app\common\model\StoreWeixin;
use app\common\model\Store;
use app\common\util\Util;
use think\Db;
use think\Model;
use think\Request;
use app\common\service\WeixinService;

class SystemService extends BaseService
{

    /*
     * 上传微信证书，上传到网站根目录
     */
    public function uploadFile(Request $request)
    {
        if ($request->file('wxfile')) {
            $file = $request->file('wxfile'); //上传微信证书
            if (empty($file)) {
                return ['status' => 0, 'msg' => '请选择上传的文件'];
            }

            $path = './';
            $info = $file->validate(['size' => 2 * 1024 * 1024, 'ext' => 'txt'])->move($path, '');

            if ($info) {
                $res = db('store_weixin')
                    ->where(['sid' => $request->param('sid')])
                    ->update(['weixin_cert' => 1]);

                if ($res === false) {
                    return ['status' => 0, 'msg' => '上传失败'];
                } else {
                    return ['status' => 1, 'msg' => '上传成功'];
                }
            } else {
                return ['status' => 0, 'msg' => '上传失败', 'data' => $file->getError()];
            }
        } else {
            return ['status' => 0, 'msg' => '请选择上传的文件'];
        }
    }

    /*
     * 修改微信表设置
     */
    public function EditWxInfo(Request $request)
    {

        if ($request->has('pub_name')) {
            $save['pub_name'] = $request->param('pub_name');
        }
        if ($request->has('source_id')) {
            $save['source_id'] = $request->param('source_id');
        }
        if ($request->has('pub_account')) {
            $save['pub_account'] = $request->param('pub_account');
        }
        if ($request->has('appid')) {
            $save['appid'] = $request->param('appid');
        }
        if ($request->has('appsecret')) {
            $save['appsecret'] = $request->param('appsecret');
        }
        if ($request->has('wxtype')) {
            $save['wxtype'] = $request->param('wxtype');
        }

        $where = [
            'sid' => $request->param('sid')
        ];
        $storeWeixinModel = new StoreWeixin();
        $res = $storeWeixinModel->where($where)->update($save);
        if ($res === false) {
            return ['status' => 0, 'msg' => '修改失败'];
        } else {
            return ['status' => 1, 'msg' => '修改成功'];
        }

    }

    /*
     * 修改store表设置
     */
    public function EditStoreInfo(Request $request)
    {
        //分销商推荐
        if ($request->has('recommend_dis')) {
            $save['recommend_dis'] = intval($request->param('recommend_dis'));
        }
        //无上线会员重置上线
        if ($request->has('reset_parents')) {
            $save['reset_parents'] = intval($request->param('reset_parents'));
        }
        //页面授权
        if ($request->has('oauth')) {
            $save['oauth'] = intval($request->param('oauth'));
        }
        //个人微信授权
        if ($request->has('oauth_self')) {
            $save['oauth_self'] = intval($request->param('oauth_self'));
        }
        // 小图
        if ($request->has('logo_small')) {
            $save['logo_small'] = $request->param('logo_small');
        }
        // 大图
        if ($request->has('logo')) {
            $save['logo'] = $request->param('logo');
        }
        // 公司名称
        if ($request->has('store_name')) {
            $save['store_name'] = $request->param('store_name');
        }
        // 地址
        if ($request->has('address')) {
            $save['address'] = $request->param('address');
        }
        // 电话号码
        if ($request->has('phone')) {
            $save['phone'] = $request->param('phone');
        }
        //购买设置
        if ($request->has('purchase_contract')) {
            $save['purchase_contract'] = $request->param('purchase_contract');
        }

        $where = [
            'store_id' => $request->param('sid')
        ];
        $storeModel = new Store();
        $res = $storeModel->where($where)->update($save);
        if ($res === false) {
            return ['status' => 0, 'msg' => '修改失败'];
        } else {
            return ['status' => 1, 'msg' => '修改成功'];
        }

    }

    /*
     * 获得店铺设置
     */
    public function GetStoreSetting(Request $request, $field = '*')
    {
        $sid = $request->param('sid');
        $where = ['s.store_id' => $sid];
        $data = db()->name('store')->alias('s')
            ->join('store_weixin sw', 'sw.sid = s.store_id', 'left')
            ->join('store_setting ss', 'ss.sid = s.store_id', 'left')
            ->where($where)
            ->field($field)
            ->find();
        if (strpos($field, 'domain') !== false) {
            $site_url = $data['domain'] == '' ? $_SERVER['HTTP_HOST'] : $data['domain'];
            $data['url'] = Util::http_url_path($site_url . '/api/front/weixin/token/sid/' . $request->param('sid'));
        }

        $weixin_ser = new WeixinService();
        $wechat = $weixin_ser->get_wechat($sid);
        $accessToken = $wechat->access_token;
        $data['new_token'] = $accessToken->getToken();

        return ['content' => $data];
    }

    /*
    * 添加微信设置
    */
    public function AddWxInfo(Request $request)
    {

        if ($request->has('pub_name')) {
            $save['pub_name'] = $request->param('pub_name');
        }
        if ($request->has('source_id')) {
            $save['source_id'] = $request->param('source_id');
        }
        if ($request->has('pub_account')) {
            $save['pub_account'] = $request->param('pub_account');
        }
        if ($request->has('appid')) {
            $save['appid'] = $request->param('appid');
        }
        if ($request->has('appsecret')) {
            $save['appsecret'] = $request->param('appsecret');
        }
        if ($request->has('wxtype')) {
            $save['wxtype'] = $request->param('wxtype');
        }
        $save['sid'] = $request->param('sid');

        $storeWeixinModel = new StoreWeixin();
        $res = $storeWeixinModel->save($save);
        if ($res === false) {
            return ['status' => 0, 'msg' => '修改失败'];
        } else {
            return ['status' => 1, 'msg' => '修改成功'];
        }

    }

    //获取商城管理员
    public function GetAdminSetting(Request $request)
    {
        $where = [
            'ui.sid' => $request->param('sid'),
            'ui.is_administrator' => 1
        ];
        $field = 'u.user_name,u.user_mobile,u.user_openid,u.user_nickname,u.user_headimgurl,ui.id,ui.sid,ui.userid,ui.is_administrator';
        $admin_list = db()->name('user_integral')
            ->alias('ui')
            ->join('user u', 'ui.userid = u.user_id', 'left')
            ->field($field)
            ->where($where)
            ->select();
        return ['content' => $admin_list];
    }

    //修改管理员
    public function EditAdminSetting($sid, $uid)
    {
        $user_nickname = db('user')->where(['user_id' => $uid])->value('user_nickname');
        ResourceDownloadService::addDownloadLog($sid, '已被更换。新管理员为:' . $user_nickname);

        $res = db('user_integral')
            ->where(['sid' => $sid])
            ->update(['is_administrator' => 0]);
        if ($res !== false) {
            $re = db('user_integral')
                ->where(['sid' => $sid, 'userid' => $uid])
                ->update(['is_administrator' => 1]);

            // 绑定成为系统超级管理员
            db('store_admin')->where(['sid' => $sid, 'status' => 1, 'is_admin' => 1])->setField('uid', $uid);
            $msgService = new WxTplMsgService();
            $msgService->send($sid, $uid, 'bind_manager');

            if ($re) {
                return ['status' => 1];
            } else {
                return ['status' => 0];
            }
        }

    }

    public function hasAdmin($sid)
    {
        return db('user_integral')->where(['sid' => $sid, 'is_administrator' => 1])->find();
    }

    //获取店铺客服配置
    public function GetCustomerInfo(Request $request)
    {
        $where = [
            'store_id' => $request->param('sid')
        ];
        $info = db('cs_setting')
            ->where($where)
            ->find();
        return ['content' => $info];
    }

    //编辑店铺客服配置
    public function EditCustomerInfo(Request $request)
    {
        $postParam = $request->post();
        $data = array();
        if ($request->has('cs_enterprise_id')) {
            $data['cs_enterprise_id'] = $postParam['cs_enterprise_id'];
        }
        if ($request->has('cs_login')) {
            $data['cs_login'] = $postParam['cs_login'];
        }
        if ($request->has('cs_pwd')) {
            $data['cs_pwd'] = $postParam['cs_pwd'];
        }
        if ($request->has('create_time')) {
            $data['create_time'] = strtotime($postParam['create_time']);
            $data['end_time'] = strtotime('+1 year', strtotime($postParam['end_time']));
        }
        $data['status'] = $postParam['status'];
        $data['update_time'] = time();
        //查找
        $where = ['store_id' => $request->param('sid')];
        $info = db('cs_setting')->where($where)->find();
        //dump($data);die;
        if (empty($info)) {
            $data['store_id'] = $request->param('sid');
            $res = db('cs_setting')->insert($data);
        } else {
            $res = db('cs_setting')->where($where)->update($data);
        }
        if ($res === false) {
            return ['status' => 0];
        } else {
            return ['status' => 1];
        }
    }

}